# -*- coding: utf-8 -*-
# standard
import os
import sys
from functools import lru_cache
from time import perf_counter
from time import time_ns
from random import randint

# third
from cachelib import SimpleCache

# local
_P_PATH =  os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if _P_PATH not in sys.path:
    sys.path.append(_P_PATH)
from toolbox.common_tools import logger


"""
@Title:   
@File: 比较常见缓存效率.py
@Author: walle 2024年10日26日 11时06分03秒
@Version: 1.0.0
@Desc: 
内存消耗上，大家都差不多
性能上 lru_cache > 全局变量 > cachelib
"""

DATA = {}
CACHE = SimpleCache()


def long_time_func1(n: int) -> int:
    # 模仿一个长耗时函数
    result = 0
    for _ in range(99999):
       result = randint(0, 10000)
    return result * n


@lru_cache(maxsize=None)
def long_time_func1_cache(n: int) -> int:
    # 模仿一个长耗时函数
    result = 0
    for _ in range(99999):
       result = randint(0, 10000)
    return result * n


def long_time_func2_cache(n: int) -> int:
    # 模仿一个长耗时函数
    if n not in DATA:
        result = 0
        for _ in range(99999):
            result = randint(0, 10000)
        result = result * n
        DATA[n] = result
    else:
        result = DATA[n]
    return result


def long_time_func3_cache(n: int) -> int:
    # 模仿一个长耗时函数
    if not (result := CACHE.get(n)):
        result = 0
        for _ in range(99999):
            result = randint(0, 10000)
        result = result * n
        CACHE.set(n, result)
    else:
        pass
    return result



if __name__ == '__main__':
    num = 2000
    for i in range(num):
        n = randint(10, int(num / 2))
        # b = time_ns()
        # long_time_func1_cache(n=n)
        # logger.info(f'lur_cache缓存过的函数耗时: {(time_ns() - b) / 1} 纳秒')
        # b = time_ns()
        # long_time_func2_cache(n=n)
        # logger.info(f'全局变量缓存过的函数耗时: {(time_ns() - b) / 1} 纳秒')
        b = time_ns()
        long_time_func3_cache(n=n)
        logger.info(f'cachelib缓存过的函数耗时: {(time_ns() - b) / 1} 纳秒')
        # b2 = time_ns()
        # long_time_func1(n)
        # logger.info(f'未缓存函数耗时: {(time_ns() - b2) / 1} 纳秒')
        logger.debug("测试完成")
    pass